#include "NetworkWorker.h"
#include <QDebug>

NetworkWorker::NetworkWorker(QObject* parent) : QObject(parent)
{
}

NetworkWorker::~NetworkWorker()
{
}

void NetworkWorker::processPacket(const QByteArray& data, const QHostAddress& sender, quint16 port)
{
    try 
    {
        // 转换为通用数据格式
        std::vector<uint8_t> universalData(data.begin(), data.end());
        
        // 尝试使用适配器管理器自动选择适配器
        auto& adapterManager = ProtocolAdapters::getGlobalAdapterManager();
        auto adapter = adapterManager.selectAdapter(universalData);
        
        if (adapter) 
        {
            // 使用适配器解析消息
            auto universalMessage = adapter->deserializeMessage(universalData);
            if (universalMessage) 
            {
                emit universalMessageProcessed(std::move(universalMessage), sender, port);
                return;
            }
        }
        
        // 回退到原有的Qt数据包处理（向下兼容）
        auto packet = GamePacket::deserialize(data);
        if (packet) 
        {
            emit packetProcessed(std::move(packet), sender, port);
        }
        else 
        {
            qWarning() << "无法识别的数据包格式，来源:" << sender.toString() << ":" << port;
        }
    } 
    catch (const std::exception& e) 
    {
        qWarning() << "数据包处理错误:" << e.what();
    }
} 